<route lang="json5">
{
  style: {
    navigationBarTitleText: '公益诉讼',
    navigationBarTextStyle: 'white', //标题栏字体颜色
    navigationBarBackgroundColor: '#0063AF', //标题栏背景色(纯色)
  },
}
</route>
<template>
  <view class="petitioneSub bg-#F4F5F9 p-30rpx w-screen h-screen box-border overflow-auto">
    <wd-form ref="form" :model="model" :rules="rules">
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">个人信息</view>
        <view class="rounded-20rpx overflow-hidden">
          <wd-input
            label="姓名"
            label-width="100px"
            prop="name"
            clearable
            v-model="model.name"
            placeholder="请输入姓名"
          />
          <wd-input
            label="手机号码"
            label-width="100px"
            prop="phone"
            clearable
            v-model="model.phone"
            placeholder="请输入手机号码"
          />
        </view>
      </view>

      <view class="mb-20rpx">
        <wd-textarea
          label="线索详情"
          label-width="100px"
          type="textarea"
          v-model="model.content"
          :maxlength="300"
          show-word-limit
          placeholder="请输入线索详情"
          clearable
          prop="content"
        />
      </view>
      <view class="mb-20rpx">
        <view class="text-#878787 pb-20rpx">上传相关材料（图片）（选填）：</view>
        <view class="rounded-20rpx p-20rpx box-border bg-#fff overflow-hidden">
          <wd-cell title-width="0rpx" prop="fileList">
            <wd-upload
              :file-list="model.fileList"
              multiple
              name="file"
              image-mode="aspectFill"
              :action="actions"
              @change="handleFileChange"
              @success="handleChange"
              class="bg-#fff"
            ></wd-upload>
          </wd-cell>
        </view>
      </view>
      <view class="mb-20rpx p-30rpx rounded-20rpx overflow-hidden bg-#fff">
        <view class="mb-20rpx text-24rpx">上传相关材料（视频）（选填）：</view>
        <view class="rounded-20rpx">
          <wd-cell>
            <view class="flex">
              <template v-if="model.videoUrl.length >= 0">
                <view class="relative mr-12px" v-for="(item, index) in model.videoUrl" :key="index">
                  <video :src="baseurl + item" class="w-80px h-80px relative"></video>
                  <view class="top--10px pos-absolute right--5px w-16px h-16px">
                    <!-- <img src="../../static/images/close.png" class="w-100% h-100%" /> -->
                    <wd-icon
                      name="error-fill"
                      size="16px"
                      custom-class="wd-upload__close"
                      @click="deleteVideo(index)"
                    ></wd-icon>
                  </view>
                </view>
              </template>
              <view @click="handleVideo" class="pos-relative">
                <view class="w-80px h-80px flex justify-center items-center videoCard">
                  <wd-icon size="35px" color="#B8B8B8" name="fill-camera"></wd-icon>
                </view>
              </view>
            </view>
          </wd-cell>
        </view>
      </view>
      <view class="footer">
        <wd-button class="bg-#0A4484" type="primary" size="large" @click="submitHandler" block>
          提交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<script setup lang="ts">
import { FormRules } from 'wot-design-uni/components/w-d-form/src/types'
import { postPublicAPI } from '@/service/index/foo'
import { useUserStore } from '@/store'
import { useToast } from 'wot-design-uni'
import _ from 'lodash'
const userStore = useUserStore()
const model = reactive<{
  name: string
  phone: string
  content: string
  type: number
  files: string[]
  fileList: Record<string, string>[]
  status: number
  businessType: string
  videoUrl: string[]
  // roleId: number
}>({
  name: userStore.userInfo.nickname,
  type: 1,
  phone: userStore.userInfo.phone,
  content: '',
  fileList: [],
  files: [],
  status: 1,
  businessType: 'gongYi',
  videoUrl: [],
  // roleId: userStore.userInfo.zhuanId,
})
const idCardUrl1File = ref([])
const idCardUrl2File = ref([])
const form = ref()
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '请输入姓名',
      pattern: /^[\u4e00-\u9fa5]+$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入姓名')
        }
      },
    },
  ],
  // videoUrl: [
  //   {
  //     required: true,
  //     message: '请选择活动视频',
  //     validator: (value) => {
  //       if (isArray(value) && value.length) {
  //         return Promise.resolve()
  //       } else {
  //         return Promise.reject()
  //       }
  //     },
  //   },
  // ],
  content: [
    {
      required: true,
      message: '请输入信访内容',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入信访内容')
        }
      },
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入正确的手机号',
      pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入手机号')
        }
      },
    },
  ],
  fileList: [
    {
      required: false,
      message: '请选择活动图片',
      validator: (value) => {
        if (Array.isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject()
        }
      },
    },
  ],
}
const fileList = ref<any[]>([])
const toast = useToast()

const baseurl = import.meta.env.VITE_SERVER_BASEURL
const actions: string = baseurl + '/app-api/infra/file/upload-id'
const action: string = baseurl + '/admin-api/infra/file/upload'
const cameraList = [
  {
    value: 'back',
    name: '后置摄像头',
    checked: 'true',
  },
  {
    value: 'front',
    name: '前置摄像头',
  },
]

const compress = true
let videoSrc = ''

const cameraIndex = 0
onLoad((options) => {
  model.type = options.type
})
function handleChange({ file }) {
  const { data } = JSON.parse(file.response)
  model.files.push(data)
}
function handleFileChange({ fileList }) {
  model.fileList = fileList
}
function deleteVideo(index) {
  model.videoUrl.splice(index, 1)
}

function handleVideo() {
  uni.chooseVideo({
    maxDuration: 60, // 最大为60秒
    count: 1,
    compressed: true,
    camera: cameraList[cameraIndex].value,
    sourceType: ['album', 'camera'],
    success: (res) => {
      const videoFile = res.tempFilePath
      videoSrc = res.tempFilePath
      console.log('res', res)
      if (compress && res.size / 10240 > 1025) {
        console.log('压缩')
        videoCompress(res.tempFilePath)
        console.log('压缩后')
      } else {
        videoUpload(res.tempFilePath)
      }
    },
  })
}
function videoCompress(tempFilePath) {
  toast.loading({
    msg: '压缩中...',
  })

  uni.compressVideo({
    src: tempFilePath,
    quality: 'low', // 'low':低，'medium':中，'high':高
    success: function (res) {
      console.log('压缩后', res)
      videoUpload(res.tempFilePath)
    },
    fail: function (err) {
      toast.error({
        msg: '视频压缩失败',
      })
    },
  })
}
function videoUpload(tempFilePath) {
  toast.loading({
    msg: '上传中...',
  })
  const uploadTask = uni.uploadFile({
    url: '/app-api/infra/file/upload', // 自己文件上传的路径
    method: 'POST',
    filePath: tempFilePath,
    name: 'file',
    success: (res) => {
      const { data } = JSON.parse(res.data)
      model.videoUrl.push(data)
      if (JSON.parse(res.data).data) {
        toast.success({
          msg: '上传成功',
        })
      }
    },
    fail: (err) => {
      console.log(err)
      toast.close()
      toast.error({
        msg: err,
      })
    },
    complete: () => {},
  })
  uploadTask.onProgressUpdate((res) => {
    toast.loading({
      msg: '上传中' + res.progress + '%',
    })
    if (res.progress == 100) {
      toast.close()
    }
  })
}
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        try {
          postPublicAPI({
            openId: userStore.userInfo.openid,
            ...model,
            fileList: undefined,
            files: [...model.files],
            videoUrl: model.videoUrl.join(','),
          }).then((res) => {
            if (res.code == 0) {
              toast.success({
                msg: '操作成功',
                duration: 0,
              })
            } else {
              toast.error({
                msg: res.msg,
                duration: 0,
              })
            }

            setTimeout(() => {
              uni.navigateBack({
                delta: 2,
              })
              toast.close()
            }, 1500)
          })
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>
<style lang="scss" scoped>
::v-deep .wd-upload {
  background: #fff;
}

::v-deep .wd-cell {
  padding-left: 0rpx !important;
}

::v-deep .wd-cell__wrapper {
  padding: 10rpx !important;
}

::v-deep .wd-cell__left {
  flex: none !important;
  margin-right: 5rpx !important;
}

::v-deep .wd-cell__value {
  text-align: left !important;
}

::v-deep .wd-icon {
  color: #aaa8a8;
}

.videoCard {
  background: rgba(0, 0, 0, 0.04);
}

::v-deep .wd-icon-sound {
  margin-right: 20rpx;
}
</style>
